<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Address;
use app\common\model\Category;
use app\common\model\Order as orderModel;
use app\common\model\Goods as goodsModel;
use app\common\model\GoodsAttr;
use app\common\model\GoodsComment;
use app\common\model\OrderGoods;
use app\common\model\User;
use think\Db;
use Logistics\Logistics;
/**
 * 订单接口
 */
class Order extends Api
{
    public function _initialize()
    {
        parent::_initialize();
    }
    /**
     * 订单列表
     * @param varchar $token Token
     * @param varchar $status 状态:7=全部，0=待付款,1=待发货,2=待收货,3=已完成,4=申请退款,5=已退款,6=退款失败
     * @param int $page 页数，默认1
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1618976008",
    "data": [
    {
    "id": 3,订单ID
    "order_sn": "zm45465123165456",订单号
    "status": 2,状态:0=待付款,1=待发货,2=待收货,3=已完成,4=申请退款,5=已退款,6=退款失败
    "actual_price": "80.00",支付总金额
    "reason": "",退款失败原因
    "goods_status": 0,订单下的商品0单个商品1多个商品
    "goods_info": {商品信息：
    "goods_image": "http://www.shop.com/uploads/20200908/7f8361873663225fc7454a3120cc729d.png",goods_status=0时为字符串，goods_status=1时为数组
    "goods_name": "娃娃菜",商品名称
    "attr_name": "三颗"规格
    },
    "status_text": "Status 2",
    "paytime_text": ""
    },
    {
    "id": 2,
    "order_sn": "zm45465123165456",
    "status": 2,
    "actual_price": "80.00",
    "goods_status": 0,
    "goods_info": {
    "goods_image": "http://www.shop.com/uploads/20200908/7f8361873663225fc7454a3120cc729d.png",
    "goods_name": "娃娃菜",
    "attr_name": "三颗"
    },
    "status_text": "Status 2",
    "paytime_text": ""
    },
    {
    "id": 1,
    "order_sn": "zm45465123165456",
    "status": 2,
    "actual_price": "80.00",
    "goods_status": 0,
    "goods_info": {
    "goods_image": [
    "http://www.shop.com/uploads/20200908/7f8361873663225fc7454a3120cc729d.png",
    "http://www.shop.com/uploads/20200908/b32efe21e1f7a2d721f371fd0e94bf1b.png"
    ]
    },
    "status_text": "Status 2",
    "paytime_text": ""
    }
    ]
    })
     */
    public function order_list()
    {
        $token = $this->request->get('token');
        $status = $this->request->get('status')==null?5:$this->request->get('status');
        $user = User::where('token',$token)->field('id')->find();
        $pagesize = 10;
        $page  = $this->request->get('page')==null?1:$this->request->get('page');
        $page = ($page-1)*$pagesize;
        $where['userid'] = array('eq',$user['id']);
        if($status != 7){
            $where['status'] = array('eq',$status);
        }
        $list = orderModel::where($where)->field('id,order_sn,status,actual_price,reason')->order('createtime desc')->limit($page,$pagesize)->select();
        foreach($list as &$value){
            $order_goods = collection(OrderGoods::where('order_id',$value['id'])->order('id asc')->select())->toArray();
            $goods_info = $goods_images = array();
            $goods_count = 0;
            if(count($order_goods) == 1){
                $value['goods_status'] = 0;
                $goods_info  =[
                    'goods_name'=>$order_goods[0]['goods_name'],
                    'attr_name'=>$order_goods[0]['attr_name']
                ];
                $goods_images[0]=$this->domain.$order_goods[0]['goods_image'];
                $goods_info['goods_images'] = $goods_images;
            }elseif(count($order_goods) > 1){
                $value['goods_status'] = 1;
                foreach($order_goods as &$v1){
                    $goods_images[] = $this->domain.$v1['goods_image'];
                    $goods_count +=$v1['num'];
                }
                $goods_info['goods_images'] = $goods_images;
                $goods_info['goods_count'] = $goods_count;
            }
            $value['goods_info'] = $goods_info;
        }
        $this->success($list);
    }
    /**
     * 订单详情
     * @param varchar $token Token
     * @param varchar $id 订单ID
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1618976719",
    "data": {
    "id": 1,
    "order_sn": "zm45465123165456",订单号
    "userid": 1,
    "price": "100.00",总价
    "discounted_price": "20.00",
    "actual_price": "80.00",实际支付价格
    "status": 2,状态:0=待付款,1=待发货,2=待收货,3=已完成,4=申请退款,5=已退款,6=退款失败
    "createtime": "2021-04-07 09:50",下单时间
    "shiptime": "2021-04-07 09:50",发货时间
    "username": "张三",姓名
    "mobile": "13411112222",手机号
    "address": "河南省郑州市金水区外环路",收货地址
    "is_coupon": 0,
    "note": "可以的，没事",备注
    "paytype": 1,
    "paytime": 0,
    "courier_company": "圆通速递",
    "courier_code": "yuantong",
    "tracking_number": "443234455456546",
    "reason": "",退款驳回原因
    "order_goods": [订单商品
    {
    "id": 1,
    "order_id": "1",
    "goods_id": 0,
    "attr_id": 0,
    "goods_image": "http://www.shop.com/uploads/20200908/7f8361873663225fc7454a3120cc729d.png",商品图片
    "goods_name": "娃娃菜",商品名称
    "attr_name": "三颗",商品规格
    "unit_price": "25.00",单价
    "num": 1,数量
    "createtime": 1599120081
    },
    {
    "id": 2,
    "order_id": "1",
    "goods_id": 0,
    "attr_id": 0,
    "goods_image": "http://www.shop.com/uploads/20200908/b32efe21e1f7a2d721f371fd0e94bf1b.png",
    "goods_name": "冻豆腐",
    "attr_name": "一颗",
    "unit_price": "10.00",
    "num": 2,
    "createtime": 1599120081
    }
    ],
    "status_text": "Status 2",
    "paytime_text": "1970-01-01 08:00:00"
    }
    })
     */
    public function order_detail()
    {
        $token = $this->request->get('token');
        $id = $this->request->get('id');
        $user = User::where('token',$token)->field('id')->find();
        $order_info = orderModel::where(['userid'=>$user['id'],'id'=>$id])->find();
        if($order_info){
            $order_info['createtime'] = date('Y-m-d H:i',$order_info['createtime']);
            //订单商品
            $order_goods = OrderGoods::where('order_id',$order_info['id'])->order('id asc')->select();
            foreach($order_goods as &$value){
                $value['goods_image'] = $this->domain.$value['goods_image'];
            }
            $order_info['order_goods'] = $order_goods;
            $this->success($order_info);
        }
        $this->error('暂无数据');
    }
    /**
     * 查看物流
     * @param varchar $token Token
     * @param varchar $id 订单ID
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1618977271",
    "data": {
    "info": {
    "courier_company": "圆通速递",快递名称
    "tracking_number": "443234455456546"快递单号
    },
    "data": [快递信息
    {
    "time": "2021-04-21 11:54:31",时间
    "status": "已发货",状态
    "context": "包裹正在等待快递小哥揽收~"内容
    }
    ]
    }
    })
     */
    public function logistics($ids = null)
    {
        $token = $this->request->get('token');
        $id = $this->request->get('id');
        $user = User::where('token',$token)->field('id')->find();
        $Logistics = new Logistics();
        $info = orderModel::where(['userid'=>$user['id'],'id'=>$id])->find();
        if (empty($info)) {
            $this->error(__('暂无数据'));
        }
        if($info['status'] <=1){
            $this->error('暂无数据');
        }
        if($info['courier_code'] == '' || $info['tracking_number'] == '' ){
            $this->error('参数不正确');
        }
        $expressinfo = json_decode($Logistics->getlogistics($info['courier_code'], $info['tracking_number']), true);
        //print_r($expressinfo);exit;
        if(isset($expressinfo['returnCode']) && $expressinfo['returnCode'] != 200){
            $this->error($expressinfo['message']);
        }
        if (!isset($expressinfo['data'])) {
            $expressinfo['data'][] = [
                'time' => date('Y-m-d H:i:s'),
                'status' => '已发货',
                'context' => '包裹正在等待快递小哥揽收~'
            ];
        }
        $expressinfo['info']['courier_company'] =$info['courier_company'];
        $expressinfo['info']['tracking_number'] =$info['tracking_number'];
        /*$expressinfo['data'][] = [
            'time' => date('Y-m-d H:i:s'),
            'status' => '已发货',
            'context' => '包裹正在等待快递小哥揽收~'
        ];*/
        $this->success($expressinfo);
    }
    /**
     * 确认收货
     * @ApiMethod   (POST)
     * @param string $id   订单ID
     * @param string $token      用户token
     * @ApiReturn   ({
    "code": 1,
    "msg": "操作成功",
    "time": "1619081407",
    "data": ""
    })
     */
    public function success_order()
    {
        $token = $this->request->post('token');
        $order_id = $this->request->post('id');
        $user_info = User::where('token',$token)->field('id')->find();
        $order_info = orderModel::where(['id'=>$order_id,'userid'=>$user_info['id']])->find();
        if($order_info){
            if($order_info['status'] != 2){
                $this->error('订单状态错误');
            }
            Db::startTrans();
            try {
                $res = orderModel::where('id',$order_info['id'])->update(['status'=>3]);

                Db::commit();
            } catch (Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
                return false;
            }
            if($res){

                $this->success('','操作成功');
            }else{
                $this->error('操作失败');
            }
        }else{
            $this->error('数据异常');
        }
    }
    /**
     * 立即支付
     * @ApiMethod   (POST)
     * @param string $token 用户token
     * @param string $id 订单ID
     * @param string $type 1支付宝2微信
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1596684503",
    "data": []
    })
     */
    public function buy_now()
    {
        $token = $this->request->post('token');
        $user_info = User::where('token', $token)->field('id')->find();
        $order_id = $this->request->post('id');
        $type = $this->request->post('type');
        $goods_info =orderModel::where('id',$order_id)->where('userid',$user_info['id'])->find();
        if ($goods_info) {
            if($goods_info['status'] != 0){
                $this->error('只有未付款的订单才可支付');
            }
            //查看该订单下的商品
            $order_goods = Db::name('order_goods')->where('order_id',$goods_info['id'])->select();
            foreach ($order_goods as &$value) {
                $goods_attr = GoodsAttr::where('id',$value['attr_id'])->where('goods_id',$value['goods_id'])->find();
                if(empty($goods_attr)){
                    $this->error($value['goods_name'].'商品异常，请重新下单');
                }
                if ($value['num'] > $goods_attr['stock']) {
                    $this->error($value['goods_name'].'购买数量大于库存');
                }
                if($value['unit_price'] != $goods_attr['price']){
                    $this->error($value['goods_name'].'价格变动，请重新下单');
                }
            }
            //修改订单号
            $data = [
                'order_sn'=>getOrderSn(),
                'paytype'=>$type,
            ];
            Db::startTrans();
            try {
                $res = Order::where('id',$goods_info['id'])->update($data);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if($res){
                if($goods_info['actual_price'] <0.01){
                    $this->error('支付错误');
                }
                if($type == 1){
                    //支付宝支付
                    $title = '订单信息'.$data['order_sn'];
                    $amount = abs($data['actual_price']);
                    $notify_url =  $this->request->root(true) . '/api/pays/goods_response/type/alipay';

                    $result = \addons\epay\library\Service::submitOrder($amount,$data['order_sn'],'alipay',$title,$notify_url,'','app');

                    //$result = ali_pay($title,$notify_url,$amount,$data['zong_order_sn']);
                    $this->success($result);
                }elseif($type ==2){
                    //微信支付
                    $title = '订单信息'.$data['zong_order_sn'];
                    $amount = abs($data['actual_price']);
                    $notify_url =  $this->request->root(true) . '/api/pays/goods_response/type/wechat';
                    $result = \addons\epay\library\Service::submitOrder($amount,$data['order_sn'],'wechat',$title,$notify_url,'','app');
                    //$result = wechat_pay($title,$notify_url,$amount,$data['zong_order_sn']);
                    $this->success($result);
                }
            }
        }
        $this->error('数据异常');
    }
    /**
     * 申请退款
     * @ApiMethod   (POST)
     * @param string $id   订单ID
     * @param string $token      用户token
     * @param string $refund_reason      退款原因
     * @param string $supplementary_description      补充描述
     * @param string $refund_images      相关图片,逗号隔开
     * @ApiReturn   ({
    "code": 200,
    "msg": "申请提交成功",
    "data": ""
    })
     */
    public function apply_refund()
    {
        $token = $this->request->post('token');
        $order_id = $this->request->post('id');
        $refund_reason = $this->request->post('refund_reason');
        $supplementary_description = $this->request->post('supplementary_description');
        $refund_images = $this->request->post('refund_images');
        $user_info = User::where('token',$token)->field('id')->find();
        $order_info = orderModel::where(['id'=>$order_id,'userid'=>$user_info['id']])->find();
        if($order_info){
            if(!in_array($order_info['status'],[1,2,3])){
                $this->error('该订单不能退款');
            }
            if($refund_reason == null){
                $this->error('请选择退款原因');
            }
            $data = [
                'refund_reason'=>$refund_reason,
                'supplementary_description'=>$supplementary_description,
                'refund_images'=>$refund_images,
                'status'=>4,
            ];
            Db::startTrans();
            try {
                $res = orderModel::where('id',$order_info['id'])->update($data);
                Db::commit();
            } catch (Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
                return false;
            }
            if($res){
                $this->success('','申请成功');
            }else{
                $this->error('申请失败');
            }
        }else{
            $this->error('数据异常');
        }
    }
}